package com.example.videolib

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import com.example.videolib.databinding.ViewLayoutProgressControlBinding

class ProgressControlView : FrameLayout, View.OnClickListener {
    private val TAG = "ProgressControlView"
    val binding: ViewLayoutProgressControlBinding =
        ViewLayoutProgressControlBinding.inflate(LayoutInflater.from(context), this, true)

    var playListener: OnPlayListener? = null
    private var mTotalTime: Long = 0L
    private var mCurrentTime: Long = 0L

    private var mLineLength = 0
    private var mGestureDetector = GestureDetector(context, SimpleListener())
    private val mHandler = Handler(Looper.myLooper()!!) {
        binding.viewProgressControlCl.visibility = View.GONE
        binding.viewProgressViewMoveLl.visibility = View.GONE
        false
    }


    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    @SuppressLint("ClickableViewAccessibility")
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
            super(context, attrs, defStyleAttr) {
        binding.apply {
            viewProgressStartOrPauseCb.setOnCheckedChangeListener { _, isCheck ->
                if (isCheck) {
                    playListener?.start()
                } else {
                    playListener?.pause()
                }
            }
            viewProgressCirculationTv.setOnClickListener {
                playListener?.circulation()
            }
            mLineLength = context.resources.displayMetrics.widthPixels - 70.dp2px
            viewProgressRootLayout.setOnTouchListener { view, event ->
                mGestureDetector.onTouchEvent(event)
            }
            viewProgressAdd.setOnClickListener(this@ProgressControlView)
            viewProgressReduce.setOnClickListener(this@ProgressControlView)
            viewProgressExpand.setOnClickListener(this@ProgressControlView)
            viewProgressUp.setOnClickListener(this@ProgressControlView)
            viewProgressDown.setOnClickListener(this@ProgressControlView)
            viewProgressNarrow.setOnClickListener(this@ProgressControlView)
        }
    }

    fun setTotalLength(length: Long) {
        Log.d(TAG, "setTotalLength: $length")
        mTotalTime = length
        binding.viewProgressProgressTv.text = "00:00:00 / ${ms2sStr(mTotalTime)}"
    }

    fun setProgress(currentPosition: Long) {
        Log.d(TAG, "setProgress: $currentPosition")
        mCurrentTime = currentPosition
        binding.viewProgressProgressTv.text = "${ms2sStr(mCurrentTime)} / ${ms2sStr(mTotalTime)}"
        updateLine()
    }

    private fun updateLine() {
        val params = binding.viewProgressProgressBarV.layoutParams
        Log.d(TAG, "updateLine=========:${mTotalTime - mCurrentTime} ")
        if ((mTotalTime - mCurrentTime) > 300) {
            val proportion = mCurrentTime.toFloat() / mTotalTime
            params.width = (mLineLength * proportion).toInt()
        } else {
            params.width = ViewGroup.LayoutParams.MATCH_PARENT
        }
        binding.viewProgressProgressBarV.layoutParams = params
    }

    interface OnPlayListener {
        fun start()
        fun pause()
        fun circulation()
        fun moveto(index: Long)
        fun add()
        fun reduce()
        fun expand()
        fun narrow()
        fun up()
        fun down()
    }

    private fun ms2sStr(length: Long): String {
        val total: Long = length / 1000
        val s: Long = total % 60
        val m: Long = total / 60
        val h: Long = m / 60
        return "${fillZero(h)}:${fillZero(m)}:${fillZero(s)}"
    }

    private fun fillZero(num: Long): String {
        if (num < 10) {
            return "0$num"
        }
        return num.toString()
    }

    private fun sendEmptyMessageDelayed() {
        mHandler.removeMessages(0)
        mHandler.sendEmptyMessageDelayed(0, 5000)
    }

    inner class SimpleListener : GestureDetector.SimpleOnGestureListener() {

        override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
//            显示菜单
            binding.viewProgressControlCl.visibility = View.VISIBLE
            binding.viewProgressViewMoveLl.visibility = View.VISIBLE
            sendEmptyMessageDelayed()
            return super.onSingleTapConfirmed(e)
        }

        override fun onScroll(
            e1: MotionEvent?,
            e2: MotionEvent?,
            distanceX: Float,
            distanceY: Float
        ): Boolean {
            Log.d(TAG, "onScroll: ")
            return super.onScroll(e1, e2, distanceX, distanceY)
        }

        override fun onFling(
            e1: MotionEvent, e2: MotionEvent,
            velocityX: Float, velocityY: Float
        ): Boolean {
            //快进 快退
            val x1 = e1.x
            val y1 = e1.y
            val x2 = e2.x
            val y2 = e2.y
            when {
                y1 - y2 > 150 -> {
                    Log.d(TAG, "onTouchEvent: 向上滑")
                }
                y2 - y1 > 150 -> {
                    Log.d(TAG, "onTouchEvent: 向下滑")
                }
                x1 - x2 > 50 -> {
                    Log.d(TAG, "onTouchEvent: 向左滑")
                }
                x2 - x1 > 50 -> {
                    Log.d(TAG, "onTouchEvent: 向右滑")
                }
            }
            sendEmptyMessageDelayed()
            return super.onFling(e1, e2, velocityX, velocityY)
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            //放大缩小 六个档位   1 0.9 0.8 0.7 0.6 0.5
            R.id.view_progress_add -> {
//                放大
                playListener?.add()
            }
            R.id.view_progress_reduce -> {
//                缩小
                playListener?.reduce()
            }
            R.id.view_progress_expand -> {
//                左右阔
                playListener?.expand()
            }
            R.id.view_progress_narrow -> {
//                左右缩
                playListener?.narrow()
            }
            R.id.view_progress_up -> {
//                向上
                playListener?.up()
            }
            R.id.view_progress_down -> {
//                向下
                playListener?.down()
            }
        }
    }
}
